package org.example.analysis.service.analyzer;

import lombok.extern.slf4j.Slf4j;
import org.example.analysis.service.dataobj.ClassDataObject;
import org.example.analysis.service.dataobj.ProjectDataObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 类分析器 - 负责分析Java源代码文件，提取类信息
 */
@Slf4j
public class ProjectAnalyzer {
    
    /**
     * 分析Java源代码目录，生成class,method,field等信息
     *
     * @param sourceDir 源代码目录
     * @return 项目分析结果
     */
    public ProjectDataObject analyzeCode(File sourceDir) {
        if (!sourceDir.exists() || !sourceDir.isDirectory()) {
            log.error("源代码目录不存在或不是目录: {}", sourceDir.getAbsolutePath());
            return new ProjectDataObject();
        }
        
        ProjectDataObject project = new ProjectDataObject();
        project.setSourceDir(sourceDir.getAbsolutePath());
        project.setProjectName(sourceDir.getName());
        project.setAnalysisStartTime(new Date());
        project.setAnalysisStatus("ANALYZING");
        
        try {
            // 分析所有Java文件
            List<ClassDataObject> classInfoList = new ArrayList<>();
            analyzeDirectory(sourceDir, classInfoList);
            
            project.setClassDataObjects(classInfoList);
            updateProjectStats(project);
            
            project.setAnalysisStatus("COMPLETED");
            project.setAnalysisEndTime(new Date());
            log.info("代码分析完成，共分析{}个类", classInfoList.size());
            return project;
            
        } catch (Exception e) {
            project.setAnalysisStatus("FAILED");
            project.setErrorMessage(e.getMessage());
            project.setAnalysisEndTime(new Date());
            log.error("代码分析失败", e);
            return project;
        }
    }
    
    /**
     * 递归分析目录中的Java文件
     */
    private void analyzeDirectory(File directory, List<ClassDataObject> classInfoList) {
        log.info("分析目录: {}", directory.getAbsolutePath());
        File[] files = directory.listFiles();
        if (files == null) {
            return;
        }
        
        for (File file : files) {
            if (file.isDirectory()) {
                analyzeDirectory(file, classInfoList);
            } else if (file.getName().endsWith(".java")) {
                try {
                    ClassDataObject classInfo = ClassAnalyzer.parseJavaFile(file);
                    if (classInfo != null) {
                        classInfoList.add(classInfo);
                    }
                } catch (Exception e) {
                    log.error("解析Java文件失败: {}", file.getAbsolutePath(), e);
                }
            }
        }
    }
    

    /**
     * 更新项目统计信息
     */
    private void updateProjectStats(ProjectDataObject project) {
        List<ClassDataObject> classes = project.getClassDataObjects();
        ProjectDataObject.ProjectStats stats = project.getStats();
        stats.setTotalClasses(classes.size());
        
        int totalMethods = 0;
        int totalCodeLines = 0;
        int interfaceCount = 0;
        int abstractClassCount = 0;
        int entryPointCount = 0;
        
        for (ClassDataObject classObj : classes) {
            if (classObj.isInterface()) {
                interfaceCount++;
            }
            if (classObj.isAbstract()) {
                abstractClassCount++;
            }
            
            totalCodeLines += classObj.getCodeLines();
            
            if (classObj.getMethods() != null) {
                totalMethods += classObj.getMethods().size();
                entryPointCount += classObj.getMethods().stream()
                    .filter(method -> method.isEntryPoint())
                    .count();
            }
        }
        
        stats.setTotalMethods(totalMethods);
        stats.setTotalCodeLines(totalCodeLines);
        stats.setInterfaceCount(interfaceCount);
        stats.setAbstractClassCount(abstractClassCount);
        stats.setEntryPointCount(entryPointCount);
    }
    
    /**
     * 分析单个Java文件
     *
     * @param sourceFile Java源文件
     * @return 类信息
     */
    public ClassDataObject analyzeFile(File sourceFile) {
        if (!sourceFile.exists() || !sourceFile.isFile() || !sourceFile.getName().endsWith(".java")) {
            log.error("无效的Java源文件: {}", sourceFile.getAbsolutePath());
            return null;
        }
        
        try {
            ClassDataObject classInfo = ClassAnalyzer.parseJavaFile(sourceFile);
            return classInfo;
        } catch (Exception e) {
            log.error("解析Java文件失败: {}", sourceFile.getAbsolutePath(), e);
            return null;
        }
    }
} 